import os
import sys

from settings import APP_ROOT
from instance.app_instance import app

loaded_models = set()

def load_module(name):
    __import__(name)
    loaded_models.add(name)

def unload_modules():
    for m in loaded_models:
        sys.modules.__delitem__(m)
    loaded_models.clear()

def load_modules(dir, ext='.py', names=[], fn=None, logger=None):
    '''load application modules, including model, api and blueprint'''
    for root, dirs, files in os.walk(dir):
        for file in files:
            if file.endswith(ext):
                file_name = os.path.basename(file)
                name = file_name.replace(ext, '')
                relative_path = os.path.relpath(os.path.join(root, file), APP_ROOT)
                module_path = relative_path[:-3].replace(os.sep, '.')
                if logger:
                    app.logger.debug('loading module %s...', module_path)
                if module_path not in sys.modules:
                    try:
                        m=__import__(module_path, fromlist=names)
                        loaded_models.add(module_path)
                        if fn is not None:
                            fn(m, name)
                    except ModuleNotFoundError as ex:
                        print('exception while loading %s, detail: %s' % (module_path, ex))